package com.zzf.mall.controller;

import com.alibaba.fastjson.JSON;
import com.zzf.common.constant.AuthConstant;
import com.zzf.common.constant.SmsConstant;
import com.zzf.common.exception.BizCodeEnume;
import com.zzf.common.utils.R;
import com.zzf.common.vo.MemberVO;
import com.zzf.mall.feign.MemberFeginService;
import com.zzf.mall.feign.ThirdPartFeginService;
import com.zzf.mall.vo.UserRegisterVO;
import com.zzf.mall.vo.loginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author 赵振飞
 * @Date 2022/10/18
 * @Version 1.0
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeginService thirdPartFeginService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberFeginService memberFeginService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone") String phone){
        //防止规定时间内重复发送验证码
        Object redisCode = redisTemplate.opsForValue().get(SmsConstant.SMS_CODE_PERFIX + phone);
        if (redisCode != null){
            String s = redisCode.toString();
            if (!"".equals(s)){
                Long l = Long.parseLong(redisCode.toString().split("_")[1]);
                if (System.currentTimeMillis() - l <= 60000 ){
                    // 验证码的发送间隔不足一分钟 页面给出提示
                    return R.error(BizCodeEnume.VALID_SMS_EXCEPTION.getCode(),BizCodeEnume.VALID_SMS_EXCEPTION.getMsg());
                }
            }
        }
        //生成随机验证码
        String code = UUID.randomUUID().toString().substring(0,5);
        //生成的验证码存储到redis当中
        thirdPartFeginService.sendSmsCode(phone,code);
        code = code + "_"+System.currentTimeMillis();
        System.out.println("code:"+code);
        redisTemplate.opsForValue().set(SmsConstant.SMS_CODE_PERFIX+phone,code,5, TimeUnit.MINUTES);
        return R.ok();
    }

    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVO vo, BindingResult result, Model model){
        Map<String,String> map = new HashMap<>();
        if(result.hasErrors()){
            // 提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            model.addAttribute("error",map);
            return "/reg";
        }else{
            // 验证码是否正确
            String code = (String)redisTemplate.opsForValue().get(SmsConstant.SMS_CODE_PERFIX + vo.getPhone());
            code = code.split("_")[0];
            if(!code.equals(vo.getCode())){
                // 说明验证码不正确
                map.put("code","验证码错误");
                model.addAttribute("error",map);
                return "/reg";
            }else{
                // 验证码正确  删除验证码
                redisTemplate.delete(SmsConstant.SMS_CODE_PERFIX + vo.getPhone());
                // 远程调用对应的服务 完成注册功能
                R r = memberFeginService.register(vo);
                if(r.getCode() == 0){
                    // 注册成功
                    return "redirect:http://auth.zzf.com/login.html";
                }else{
                    // 注册失败
                    map.put("msg",r.getCode()+":"+r.get("msg"));
                    model.addAttribute("error",map);
                    return "/reg";
                }
            }
        }
    }

    /**
     * 会员登录
     * @param vo 会员用户名 密码
     * @return
     */
    @PostMapping("/login")
    public String login (loginVO vo, RedirectAttributes redirectAttributes, HttpSession session){

        R r = memberFeginService.login(vo);
        if (r.getCode() == 0){
            String entityJson = (String) r.get("entity");
            MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            //登录成功
            return "redirect:http://mall.zzf.com";
        }

        redirectAttributes.addAttribute("errors",r.get("msg"));
        //登录失败，重新跳转登录界面
        return "redirect:http://auth.zzf.com/login.html";
    }
}
